from flask import Flask,jsonify,render_template,request,escape
from api import geocode,around,weatherInfo
from panduan import panduan_login
from vsearch import search4letters
from pymysql import connect
import pandas as pd

app = Flask(__name__)

names = []
address2 = []


# 调用日志记录函数
def log_request(req:'flask_request',res:str)->None:
	with open('vsearch.log','a') as log:
		print(req.form,req.remote_addr,req.user_agent,res,file=log,sep='|')

def log_address(req:'name',res:'address')->None:
	with open('address.log','a') as log:
		print(req,res,file=log,sep='|')

def look_over():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor1 = con.cursor()
	sql = "select * from student"
	cursor1.execute(sql)
	res = cursor1.fetchall()
	print(res)
	return res


# 登录页
@app.route('/login')
def login_page() -> 'html':
	return render_template('login.html',the_title ="欢迎您登录湘林的Web！")


# 登录-进入主页
@app.route('/addlogin',methods=['POST'])
def addlogin() -> 'html':
	xuehao = request.form.get("xuehao") 
	mima = request.form.get("mima")
	print(xuehao)
	print(mima)
	xuehao = int(xuehao)
	a = panduan_login(xuehao, mima)
	log_request(request,a)
	if a == "true":
		student_title = ["student_id","student_name","student_gender","student_code"]
		res=look_over()
		return render_template('biaodan.html',the_title ="周边搜索")
	else:
		return "登录失败"


# 添加账号
@app.route('/addstudentpage',methods=["GET"])
def addstudent_page() -> "html":
	return render_template("addstudentpage.html")


# 添加成功
@app.route('/addstudent',methods=["POST"])
def add_student():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor5 = con.cursor()
	student_id = request.form.get("student_id")
	student_name = request.form.get("student_name")
	student_code = request.form.get("student_code")
	sql = "insert into student set id_num='%s', name='%s',code='%s'"% (student_id, student_name,student_code)
	cursor5.execute(sql)
	con.commit()
	return render_template("addsucesspage.html")


#注销第一步
@app.route('/delete',methods=["GET"])
def delete_page() -> 'html':
	return render_template("deletestudent.html")


# 注销账户第二步
@app.route('/deletestudent', methods=["POST"])
def delete_student() -> 'html':
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor2 = con.cursor()
	student_id = request.form.get("student_id")
	sql = "delete from student where id_num=%s"% (student_id)
	cursor2.execute(sql)
	con.commit()
	student_title = ["student_id","student_name","student_gender","student_code"]
	res=look_over()
	return render_template('deletesuccess.html',the_title ="欢迎您登录湘林的Web！")


#修改第一步
@app.route('/xiugai',methods=["GET"])
def modify_page() -> 'html':
	return render_template("xiugaistudent.html")


#修改第二步
@app.route("/xiugaistudent",methods=["POST"])
def modify_student():
	con = connect(host="127.0.0.1",port=3306,user="root",password="123456",db="user")
	cursor3 = con.cursor()
	student_id = request.form.get("student_id")
	student_code = request.form.get("student_code")
	sql = "update student set code='%s' where id_num='%s'"% (student_code,student_id)
	cursor3.execute(sql)
	res= cursor3.fetchall()
	con.commit()
	return render_template("modifysecesspage.html",student_id=student_id,student_code=student_code) # student_name=student_name,student_gender=student_gender,


# 进入网页的首页，数据返回biaodan.html
@app.route('/1')
def entry_page2() ->'html':
	return render_template('biaodan.html',the_title='Welcome to the web!')


# 点击“搜索”后，调用高德api——geocode和around，数据返回biaodan2
@app.route('/ob',methods=['POST'])
def go_search():
	address = request.form['address']
	codes = str(geocode(address)['geocodes'][0][ 'location'])

	location = codes
	types = request.form['types']
	results = around(location,types)['pois']
	for i in results:
		names.append(i['name'])
		address2.append(i['address'])
	return render_template('biaodan2.html',res=names,the_title='为您返回的结果：',the_data=address2)


# 详情页面
@app.route('/details',methods=['POST'])
def xiangqing():
	youge = request.form["youge"]
	combine = dict(zip(names,address2))
	sql = "%s"%youge
	thedata = combine[sql]
	return render_template('biaodan3.html',res=combine,the_title='详情页：',the_data=thedata)


# 天气查询
@app.route('/weather',methods=['POST'])
def weather():
	city = request.form["city"]
	result = weatherInfo(city) ['lives'][0]
	return render_template('biaodan4.html',res=result,the_title='天气状况：')


# 查看日志
@app.route('/viewlog',)
def view_the_log() ->'html':
	with open('vsearch.log','r') as log:
		contents = []
		for line in log:
			contents.append([])
			for item in line.split('|'):
				contents[-1].append(escape(item))

	titles = ('Form Data','Remote_addr','User_agent','Results')
	return render_template('viewlog.html',
			the_title= "欢迎进入日志浏览界面！",
			the_row_titles= titles,
			the_data=contents,)

if __name__ == '__main__':
	app.run(debug=True)